<template>
	<u-popup :show="show" mode="bottom" closeOnClickOverlay :border-radius="20" @close="handleClose"
		:safe-area-inset-bottom="false">
		<view class="cart-popup">
			<!-- 购物车头部 -->
			<view class="cart-header">
				<view class="header-left">
					<u-checkbox :checked="isAllChecked" @change="handleToggleSelectAll" shape="circle"
						activeColor="#DB0000" size="24"></u-checkbox>
					<text class="select-all-text">全选</text>
				</view>
				<view class="header-right" @click="handleClearCart">
					<u-icon name="trash" size="16" color="#666666"></u-icon>
					<text class="clear-text">清空购物车</text>
				</view>
			</view>

			<!-- 购物车商品列表 -->
			<view class="cart-list">
				<!-- 加载状态 -->
				<view v-if="loading" class="loading-container">
					<u-loading-icon mode="circle" color="#DB0000" size="24"></u-loading-icon>
					<text class="loading-text">加载中...</text>
				</view>

				<!-- 购物车商品列表 -->
				<u-checkbox-group placement="column" v-model="selectIdList">
					<view class="cart-item" v-for="(item, index) in currentCartList" :key="index">
						<view class="item-checkbox">
							<u-checkbox v-model="item.checked" :name="item.id" shape="circle" activeColor="#DB0000"
								size="24"></u-checkbox>
							
						</view>
						<view class="item-image">
							<image :src="item.image" mode="aspectFill" class="item-img"></image>
						</view>
						<view class="item-info">
							<text class="item-name">{{ item.name }}</text>
							<text class="item-sales">已售{{ item.sales }}</text>
							<view class="item-bottom">
								<view class="item-price">
									<!-- 会员价格显示 -->
									<view v-if="Userinfo.vip && item.vipPrice" class="vip-price-container">
										<view class="vip-price">
											<text class="price-symbol vip-symbol">¥</text>
											<text class="price-value vip-amount">{{ item.vipPrice }}</text>
										</view>
										<view class="original-price">
											<text class="price-symbol">¥</text>
											<text class="price-value original-amount">{{ item.price }}</text>
										</view>
									</view>
									<!-- 非会员价格显示 -->
									<view v-else class="normal-price">
										<text class="price-symbol">¥</text>
										<text class="price-value">{{ item.price }}</text>
									</view>
								</view>
								<view class="quantity-controls">
									<view class="quantity-btn" @click="handleDecreaseQuantity(item)">
										<u-icon name="minus" size="12" color="#FFFFFF"></u-icon>
									</view>
									<text class="quantity-text">{{ item.quantity }}</text>
									<view class="quantity-btn" @click="handleIncreaseQuantity(item)">
										<u-icon name="plus" size="12" color="#FFFFFF"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
			</view>

			<!-- 购物车底部 -->
			<view class="cart-footer">
				<view class="footer-left">
					<view class="cart-icon">
						<image src="/static/cart_bg.png" mode=""></image>
						<view class="cart-badge" v-if="cartCount > 0">{{ cartCount }}</view>
					</view>
					<view class="total-price">
						<text class="total-text">¥{{ totalPrice }}</text>
					</view>
				</view>
				<view class="footer-right">
					<view class="checkout-btn" @click="handleCheckout">
						<text class="checkout-text">去下单</text>
					</view>
				</view>
			</view>
		</view>
	</u-popup>
</template>

<script>
	import {
		getDiningCartList,
		updateDiningCartItem,
		deleteDiningCartItem,
		clearDiningCart
	} from '@/api/restaurant.js'

	export default {
		name: 'CartPopup',
		props: {
			show: {
				type: Boolean,
				default: false
			},
			cartList: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				selectAll: false,
				internalCartList: [], // 内部购物车数据
				loading: false, // 加载状态
				selectIdList: [], // 选中的商品ID列表
				isAllChecked: false // 全选状态
			}
		},
		computed: {
			// 使用内部购物车数据或外部传入的数据
			currentCartList() {
				return this.internalCartList.length > 0 ? this.internalCartList : this.cartList;
			},
			// 购物车商品数量（只计算选中的商品）
			cartCount() {
				return this.currentCartList
					.filter(item => item.checked)
					.reduce((total, item) => total + item.quantity, 0)
			},
			// 购物车总价（支持VIP价格）
			totalPrice() {
				return this.currentCartList
					.filter(item => item.checked)
					.reduce((total, item) => {
						// 如果是会员且有会员价，使用会员价；否则使用原价
						const price = (this.Userinfo.vip && item.vipPrice) ? parseFloat(item.vipPrice) : parseFloat(item.price);
						return total + (price * item.quantity);
					}, 0)
					.toFixed(2)
			},
			// 用户信息
			Userinfo() {
				return this.$store.state.userinfo;
			}
		},
		watch: {
			// 监听购物车弹出框显示状态
			show: {
				handler(newVal) {
					if (newVal) {
						console.log('CartPopup: 购物车弹出框显示，开始加载购物车数据');
						this.loadCartData();
					}
				},
				immediate: false
			},
			// 监听选中ID列表变化
			selectIdList: {
				handler(val) {
					console.log('CartPopup: selectIdList变化', val);
					this.updateAllChecked();
					this.updateItemChecked();
				},
				immediate: true
			},
			// 监听购物车数据变化
			currentCartList: {
				handler(val) {
					console.log('CartPopup: currentCartList变化', val);
					this.updateAllChecked();
				},
				immediate: true
			}
		},
		methods: {
			// 加载购物车数据
			loadCartData() {
				const userId = this.$store.state.userid || 'user_12345'
				console.log('CartPopup: 开始加载购物车数据，用户ID:', userId);

				this.loading = true;

				getDiningCartList({
					userId: userId
				}).then(res => {
					console.log('CartPopup: 购物车API响应:', res);
					this.loading = false;

					if (res.code == 200) {
						// 格式化购物车数据，将API字段映射为组件期望的字段
						const formattedCartList = this.formatCartData(res.data || []);
						this.internalCartList = formattedCartList;
						console.log('CartPopup: 购物车数据已更新:', this.internalCartList);

						// 初始化选中状态
						this.selectIdList = [];

						// 通知父组件购物车数据已更新
						this.$emit('cart-data-updated', this.internalCartList);
					} else {
						console.log('CartPopup: 购物车API返回错误:', res.message);
						uni.showToast({
							title: res.message || '获取购物车数据失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('CartPopup: 获取购物车数据失败:', err);
					this.loading = false;
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				});
			},

			// 格式化购物车数据
			formatCartData(cartData) {
				return cartData.map(item => ({
					id: item.id,
					name: item.productName || item.name || '未知商品',
					image: item.productImg || item.image || '/static/index/test.png',
					price: item.price || '0.00',
					sales: item.saleCount || item.sales || 0,
					quantity: item.count || item.quantity || 1,
					checked: item.checked !== undefined ? item.checked : false,
					spec: Array.isArray(item.productSpec) ? item.productSpec.join('/') : (item.productSpec ||
						item.spec || '默认规格'),
					// flavor: item.flavor || '默认口味',
					// 保留原始数据字段，用于API调用
					productId: item.productId,
					attributeIds: item.attributeIds,
					stock: item.stock,
					vipPrice: item.vipPrice,
					createTime: item.createTime,
					updateTime: item.updateTime,
					userId: item.userId
				}));
			},

			// 关闭弹出框
			handleClose() {
				this.$emit('close');
			},

			// 全选/取消全选
			handleToggleSelectAll(e) {
				console.log('CartPopup: 全选事件触发，当前值:', e);
				if (e) {
					// 全选：将所有商品ID添加到selectIdList
					this.selectIdList = this.currentCartList.map(item => item.id);
				} else {
					// 取消全选：清空selectIdList
					this.selectIdList = [];
				}
				console.log('CartPopup: 全选状态已更新，selectIdList:', this.selectIdList);
				// 通知父组件
				this.$emit('toggle-select-all', e);
			},

			// 更新商品选中状态（根据selectIdList）
			updateItemChecked() {
				this.currentCartList.forEach(item => {
					item.checked = this.selectIdList.includes(item.id);
				});
			},

			// 增加商品数量
			handleIncreaseQuantity(item) {
				// 直接更新本地数据
				item.quantity += 1;
				// 调用API更新服务器数据
				this.updateCartItemQuantity(item);
				this.$emit('increase-quantity', item);
			},

			// 减少商品数量
			handleDecreaseQuantity(item) {
				if (item.quantity > 1) {
					// 直接更新本地数据
					item.quantity -= 1;
					// 调用API更新服务器数据
					this.updateCartItemQuantity(item);
					this.$emit('decrease-quantity', item);
				} else {
					// 数量为1时，删除商品
					this.deleteCartItem(item);
				}
			},

			// 更新购物车商品数量
			updateCartItemQuantity(item) {
				updateDiningCartItem({
					id: item.id,
					count: item.quantity,
					price: item.price,
					attributeIds: item.attributeIds || ''
				}).then(res => {
					if (res.code == 200) {
						console.log('CartPopup: 购物车商品数量更新成功');
					} else {
						console.log('CartPopup: 购物车商品数量更新失败:', res.message);
						uni.showToast({
							title: res.message || '更新失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('CartPopup: 更新购物车商品数量失败:', err);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				});
			},

			// 删除购物车商品
			deleteCartItem(item) {
				deleteDiningCartItem({
					ids: item.id
				}).then(res => {
					if (res.code == 200) {
						// 从本地列表中移除
						const index = this.internalCartList.findIndex(cartItem => cartItem.id === item.id);
						if (index > -1) {
							this.internalCartList.splice(index, 1);
						}
						// 通知父组件
						this.$emit('cart-data-updated', this.internalCartList);
						uni.showToast({
							title: '已删除',
							icon: 'success'
						});
					} else {
						uni.showToast({
							title: res.message || '删除失败',
							icon: 'none'
						});
					}
				}).catch(err => {
					console.error('CartPopup: 删除购物车商品失败:', err);
					uni.showToast({
						title: '网络错误',
						icon: 'none'
					});
				});
			},

			// 清空购物车
			handleClearCart() {
				uni.showModal({
					title: '提示',
					content: '确定要清空购物车吗？',
					success: (res) => {
						if (res.confirm) {
							const userId = this.$store.state.userid || 'user_12345';
							clearDiningCart({
								userId: userId
							}).then(res => {
								if (res.code == 200) {
									this.internalCartList = [];
									// 通知父组件
									this.$emit('cart-data-updated', this.internalCartList);
									uni.showToast({
										title: '已清空购物车',
										icon: 'success'
									});
								} else {
									uni.showToast({
										title: res.message || '清空失败',
										icon: 'none'
									});
								}
							}).catch(err => {
								console.error('CartPopup: 清空购物车失败:', err);
								uni.showToast({
									title: '网络错误',
									icon: 'none'
								});
							});
						}
					}
				});
			},

			// 去下单
			handleCheckout() {
				const selectedItems = this.currentCartList.filter(item => this.selectIdList.includes(item.id));
				if (selectedItems.length === 0) {
					uni.showToast({
						title: '请选择要下单的商品',
						icon: 'none'
					});
					return;
				}
				
				// 先关闭弹出框
				this.handleClose();
				// 为选中的商品添加购物车ID信息
				const itemsWithCartIds = selectedItems.map(item => ({
					...item,
					cartId: item.id, // 使用购物车记录ID作为cartId
					productId: item.productId || item.id // 确保有productId字段
				}));
				
				console.log('CartPopup: 准备下单的商品数据:', itemsWithCartIds);
				
				// 获取餐桌号
				const tableNo = this.$store.state.tableNo || 0;
				console.log('CartPopup: 获取到的餐桌号:', tableNo);
				
				// 跳转到确认下单页面，传递餐桌号
				const itemsParam = encodeURIComponent(JSON.stringify(itemsWithCartIds));
				uni.navigateTo({
					url: `/pagesA/order-confirmation/order-confirmation?items=${itemsParam}&tableNo=${tableNo}`
				});
			},

			// 更新全选状态
			updateAllChecked() {
				if (this.currentCartList.length === 0) {
					this.isAllChecked = false;
					console.log('CartPopup: 购物车为空，全选状态设为false');
				} else {
					this.isAllChecked = this.currentCartList.every(item => this.selectIdList.includes(item.id));
					console.log('CartPopup: 计算全选状态', {
						商品数量: this.currentCartList.length,
						选中ID列表: this.selectIdList,
						全选状态: this.isAllChecked
					});
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 购物车弹出框样式
	.cart-popup {
		background-color: #fff;
		border-radius: 20rpx 20rpx 0 0;
		max-height: 60vh;
		min-height: 40vh;
		display: flex;
		flex-direction: column;

		.cart-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 40rpx;
			border-bottom: 2rpx solid #F5F5F5;
			flex-shrink: 0;

			.header-left {
				display: flex;
				align-items: center;

				.select-all-text {
					font-size: 28rpx;
					color: #333333;
					margin-left: 10rpx;
				}
			}

			.header-right {
				display: flex;
				align-items: center;

				.clear-text {
					font-size: 24rpx;
					color: #666666;
					margin-left: 8rpx;
				}
			}
		}

		.cart-list {
			flex: 1;
			overflow-y: auto;
			overflow-x: hidden;
			padding: 0 40rpx;
			-webkit-overflow-scrolling: touch;

			.loading-container {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 60rpx 0;

				.loading-text {
					margin-top: 20rpx;
					font-size: 28rpx;
					color: #666666;
				}
			}

			.cart-item {
				display: flex;
				align-items: center;
				padding: 30rpx 0;
				border-bottom: 2rpx solid #F5F5F5;

				&:last-child {
					border-bottom: none;
				}

				.item-checkbox {
					margin-right: 20rpx;
				}

				.item-image {
					width: 120rpx;
					height: 120rpx;
					border-radius: 12rpx;
					overflow: hidden;
					margin-right: 20rpx;

					.item-img {
						width: 100%;
						height: 100%;
					}
				}

				.item-info {
					flex: 1;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					height: 120rpx;

					.item-name {
						font-size: 28rpx;
						color: #333333;
						font-weight: 500;
						margin-bottom: 10rpx;
					}

					.item-sales {
						font-size: 24rpx;
						color: #A6A6A6;
						margin-bottom: 10rpx;
					}

					.item-bottom {
						display: flex;
						justify-content: space-between;
						align-items: center;

						.item-price {
							display: flex;
							align-items: baseline;

							.vip-price-container {
								display: flex;
								flex-direction: column;
								align-items: flex-start;
								
								.vip-price {
									display: flex;
									align-items: baseline;
									margin-bottom: 4rpx;
									
									.vip-symbol {
										font-size: 24rpx;
										color: #FF6B35;
									}
									
									.vip-amount {
										font-size: 32rpx;
										color: #FF6B35;
										font-weight: 600;
									}
								}
								
								.original-price {
									display: flex;
									align-items: baseline;
									
									.price-symbol {
										font-size: 20rpx;
										color: #999999;
									}
									
									.original-amount {
										font-size: 24rpx;
										color: #999999;
										font-weight: 400;
										text-decoration: line-through;
									}
								}
							}
							
							.normal-price {
								display: flex;
								align-items: baseline;
								
								.price-symbol {
									font-size: 24rpx;
									color: #DB0000;
								}

								.price-value {
									font-size: 32rpx;
									color: #DB0000;
									font-weight: 600;
								}
							}
						}

						.quantity-controls {
							display: flex;
							align-items: center;

							.quantity-btn {
								width: 48rpx;
								height: 48rpx;
								background-color: #DB0000;
								border-radius: 50%;
								display: flex;
								align-items: center;
								justify-content: center;
							}

							.quantity-text {
								font-size: 28rpx;
								color: #333333;
								margin: 0 20rpx;
								min-width: 40rpx;
								text-align: center;
							}
						}
					}
				}
			}
		}

		.cart-footer {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 30rpx 40rpx;
			border-top: 2rpx solid #F5F5F5;
			background-color: #fff;
			flex-shrink: 0;
			.footer-left {
				display: flex;
				align-items: center;

				.cart-icon {
					position: relative;
					margin-right: 20rpx;
					image{
						width:80rpx;
						height: 80rpx;
					}

					.cart-badge {
						position: absolute;
						top: -10rpx;
						right: -10rpx;
						background-color: #DB0000;
						color: #fff;
						width: 40rpx;
						height: 40rpx;
						font-size: 20rpx;
						border-radius: 100%;
						min-width: 24rpx;
						display: flex;
						align-items: center;
						justify-content: center;
						box-sizing: border-box;	
					}
				}

				.total-price {
					.total-text {
						font-size: 32rpx;
						color: #DB0000;
						font-weight: 600;
					}
				}
			}

			.footer-right {
				.checkout-btn {
					background-color: #DB0000;
					padding: 20rpx 40rpx;
					border-radius: 8rpx;

					.checkout-text {
						font-size: 28rpx;
						color: #fff;
						font-weight: 500;
					}
				}
			}
		}
	}
</style>